package com.sunxu.spring.scope;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 孙许
 * @date 2018-07-14
 * @description 自定义模仿单例
 */
public class ThreadScope implements Scope {

    private final ThreadLocal<Map<String, Object>> threadScope = ThreadLocal.withInitial(() -> new HashMap<>(16));

    @Override
    public Object get(String s, ObjectFactory<?> objectFactory) {
        // 存取委派给ThreadLocal去处理
        Map<String, Object> scope = threadScope.get();
        Object obj = scope.get(s);
        System.out.println("Get" + s);
        if (obj == null) {
            System.out.println("Not exists " + s);
            obj = objectFactory.getObject();
            scope.put(s, obj);
        }
        return obj;
    }

    @Override
    public Object remove(String s) {
        Map<String, Object> scope = threadScope.get();
        return scope.remove(s);
    }

    @Override
    public void registerDestructionCallback(String s, Runnable runnable) {

    }

    @Override
    public Object resolveContextualObject(String s) {
        return null;
    }

    @Override
    public String getConversationId() {
        return null;
    }
}
